/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "owndebug.h"
#include "ownutils.h"

// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
#include "MaCICtrl/MaCICtrlClient.hpp"

//******************************************************************************

//datatypes
struct MaCIServiceComparator
{
  bool operator()(const MaCI::MaCICtrl::SServiceEntry s1, const MaCI::MaCICtrl::SServiceEntry s2)
  {
    if (s1.gimnetid==s2.gimnetid)
    {
      if (s1.service.servicemajor==s2.service.servicemajor)
      {
        if (s1.service.serviceminor==s2.service.serviceminor)
        {
          return s1.service.type < s2.service.type;
        }
        return s1.service.serviceminor < s2.service.serviceminor;
      }
      return s1.service.servicemajor < s2.service.servicemajor;
    }
    return s1.gimnetid < s2.gimnetid;
  }
};

std::set<MaCI::MaCICtrl::SServiceEntry,MaCIServiceComparator> latestServices, previousServices;

//*****************************************************************************

// Set initial verbosity level to 1
static int verbose = 1;
//*****************************************************************************


// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************

// GIMnet parameters
static std::string gimnetAP = "asrobo.hut.fi";
static int gimnetAPPort = 50002;

//*****************************************************************************
static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(1,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(1,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}

//*****************************************************************************

static void showUsage()
{
  
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tGIMNetListener [OPTIONS]\n");
  //required command line params
  //..for gimi
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  
  //debug printing options
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

void NewServicesFound(MaCI::MaCICtrl::TServiceEntryArray &newServices)
{
  MaCI::MaCICtrl::TServiceEntryArray::iterator iter;
  printf("\nNew services online:\n\n");
  for (iter=newServices.begin(); iter!=newServices.end(); iter++)
  {
    printf("%s - %d:%d - %s - type:%d\n\n", iter->gimnetname.c_str(), iter->service.servicemajor,
           iter->service.serviceminor, iter->GetMaCISL().ToMaCISLString().c_str(), iter->service.type);
  }
  
}

void ServicesDisconnected(MaCI::MaCICtrl::TServiceEntryArray &disconnectedServices)
{
  MaCI::MaCICtrl::TServiceEntryArray::iterator iter;
  printf("\nServices went offline:\n\n");
  for (iter=disconnectedServices.begin(); iter!=disconnectedServices.end(); iter++)
  {
    printf("%s - %d:%d - %s - type:%d\n\n", iter->gimnetname.c_str(), iter->service.servicemajor,
           iter->service.serviceminor, iter->GetMaCISL().ToMaCISLString().c_str(), iter->service.type);
  }
  
}

static int Run(gimi::GIMI &g, MaCI::MaCICtrl::CMaCICtrlClient &MaCIClient)
{
  
  while(run) {
    
    gimi::t_serviceList servicesList;
    MaCI::MaCICtrl::TServiceEntryArray maciList;
      
    MaCI::MaCICtrl::TServiceEntryArray newServices; //services that have come online
    MaCI::MaCICtrl::TServiceEntryArray disconnectedServices; //services that went offline
    
    printf("\nPerforming servicediscovery...\n\n");
    
    if (!run)
      return 0;
    
    int result=g.serviceDiscovery(servicesList, 5000);

    if (!run)
      return 0;
      
    MaCI::EMaCIError e=MaCIClient.GetServiceArray(maciList,servicesList,5000);
      
    if (!run)
      return 0;
      
    if (result==GIMI_OK || e==MaCI::KMaCIOK)
    {
      MaCI::MaCICtrl::TServiceEntryArray::iterator iter;
      //find services that came online
      for (iter=maciList.begin(); iter!=maciList.end(); iter++)
      {
        std::pair<std::set<MaCI::MaCICtrl::SServiceEntry>::iterator,bool> p;
        //insert to previous services, return p.second=false if there already
        p=previousServices.insert(*iter);
        if (p.second)
        {
          //insert a success
          //remove it right away
          previousServices.erase(p.first);
          
          //and add to new services container
          //service was new
          newServices.push_back(*iter); 
        }
        //services from the last discovery only
        p=latestServices.insert(*iter);
        if (!(p.second))
        {
          dPrint(1,"Duplicate services from servicediscovery!");
        }
      }
      
      std::set<MaCI::MaCICtrl::SServiceEntry>::iterator iter2;
      //find services that were lost
      for (iter2=previousServices.begin(); iter2!=previousServices.end(); iter2++)
      {
        std::pair<std::set<MaCI::MaCICtrl::SServiceEntry>::iterator,bool> p;
        p=latestServices.insert(*iter2);
        if (p.second)
        {
          //
          latestServices.erase(p.first);
          //service was lost
          disconnectedServices.push_back(*iter2);
        }
      }
      
      previousServices=latestServices;
      latestServices.clear();
      
      if (newServices.size())
        NewServicesFound(newServices);
      
      if (disconnectedServices.size())
        ServicesDisconnected(disconnectedServices);
    }
  }
  
  
  
  return 0;
}


//*****************************************************************************

int main(int argc, char *argv[])
{
  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;
  
  
  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(4);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
    "\nGIMNetListener\n");


  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "g:u:p:i:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////
      
      /////////////////////////////////
      ///// GIMnet parameters ////
      /////////////////////////////////
        
      case 'u':
        gimnetAP = optarg;
        dPrint(3,"Using GIMnetAP address '%s'", optarg);
        break;
  
      case 'p':
        gimnetAPPort = atoi(optarg);
        dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
        break;
        
      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
      case 'v':
        // Increase only if not previously set to 0 (by 'quiet')
        if (verbose > 0)
          debugSetGlobalDebugLvl(++verbose);
        break;
        
      case 'q':
        verbose = 0;
        debugSetGlobalDebugLvl(0);
        break;
        
      case 'h':
      case '?':
        showUsage();
        exit(1);
        break;
        
      case -1:
        parse = false;
        break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d': '%s'",
     gimnetAP.c_str(), 
     gimnetAPPort, 
     gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d': '%s'",
     gimnetAP.c_str(), 
     gimnetAPPort,
     gimi::getGimiErrorString(r).c_str());
    
    MaCI::MaCICtrl::CMaCICtrlClient MaCIClient(&g);
    
    if (MaCIClient.Open()==MaCI::KMaCIOK)
    {
      // GIMnet connection OK and macictrl working, now just run.
      Run(g, MaCIClient);
    }
  }

  return 0;
}



